//用于上传图片
import {getFileAccessHttpUrl, uploadAction} from "@/util/api";

export const uploadMixins = {
    data() {
        return {
            //文件列表
            fileList1: []
        }
    },
    methods: {
        // 新增图片
        async afterRead(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = event.file instanceof Array ? [...event.file]:[event.file]
            let fileListLen = this[`fileList${event.name}`].length
            //遍历写入this.fileList1
            lists.forEach(item => this[`fileList${event.name}`].push({...item, status: 'uploading', message: '上传中'}))
            //循环进行上传
            for (let {url} of lists) {
                //上传图片 返回图片访问地址
                try {
                    let imgUrl = await uploadAction(url)
                    console.log(imgUrl)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: getFileAccessHttpUrl(imgUrl),
                    }))
                    fileListLen++
                } catch (e) {
                    console.log(e)
                }
            }
        },
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        //获取图片/字符串的链接地址
        getLinkStr(fileList, splitStr = ",") {
            let str = ''
            fileList.forEach(t => {
                let {url} = t
                str += splitStr + url
            })
            if (str.length > 0) {
                str = str.substring(1)
                return str
            }
            return ""
        }
    }
}

//使用
//                  <u-upload
//                       :fileList="fileList1"
//                       @afterRead="afterRead"
//                       @delete="deletePic"
//                       name="1"
//                       multiple
//                       :maxCount="3"
//                       width="50"
//                       height="50"
//                   >
//                   </u-upload>
//处理函数 form.goodsPic = form.goodsPic.map(t=>t.url).map(getOriginalFilePath).join()
